package com.rlz.framemm.util

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.net.Uri
import android.text.TextUtils
import android.view.View
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.Target
import com.rlz.base.util.ToastUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.io.*
import java.lang.Exception

/**
 * Created by RLZ
 * on 2021/11/5
 *
 */
class RxSaveImage {

    private fun saveImageAndGetPathObservable(
        context: Activity,
        url: String,
        title: String
    ): Observable<String>? {
        return Observable.create<String> { emitter -> // 检查路径
            if (TextUtils.isEmpty(url) || TextUtils.isEmpty(title)) {
                emitter.onError(Exception("请检查图片路径"))
            }
            // 检查图片是否已存在
            val appDir = context.getExternalFilesDir("shell")
            if (appDir!!.exists()) {
                val file = File(appDir, getFileName(url, title))
                if (file.exists()) {
                    emitter.onError(Exception("图片已存在"))
                }
            }
            // 没有目录创建目录
            if (!appDir.exists()) {
                appDir.mkdir()
            }
            val file = File(appDir, getFileName(url, title))
            try {
                // 下载
                val fileDo = Glide.with(context)
                    .load(url)
                    .downloadOnly(
                        Target.SIZE_ORIGINAL,
                        Target.SIZE_ORIGINAL
                    )
                    .get()
                if (fileDo != null) {
                    // 复制图片
                    copyFile(fileDo.absolutePath, file.path)

                    // 通知图库更新
                    val uri = Uri.fromFile(file)
                    val scannerIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri)
                    context.sendBroadcast(scannerIntent)
                } else {
                    emitter.onError(Exception("无法下载到图片"))
                }
            } catch (e: Exception) {
                emitter.onError(e)
            }
            emitter.onNext("")
            emitter.onComplete()
        }.subscribeOn(Schedulers.io())
    }


    @SuppressLint("CheckResult")
    fun saveImageToGallery(context: Activity, mImageUrl: String, mImageTitle: String) {
        // @formatter:off
        saveImageAndGetPathObservable(context, mImageUrl, mImageTitle)
            ?.observeOn(AndroidSchedulers.mainThread())
            ?.subscribe({
                val appDir =context.getExternalFilesDir("shell")
                val msg: String = java.lang.String.format(
                    "已保存至 %s",
                    appDir!!.absolutePath
                )
                ToastUtils.showToast(msg)
            }, { error: Throwable ->
                ToastUtils.showToast(error.message)
            })
    }

    /**
     * gif动态图以对应后缀结尾
     */
    private fun getFileName(mImageUrl: String, mImageTitle: String): String {
        return if (mImageUrl.contains(".gif")) {
            mImageTitle.replace("/".toRegex(), "-") + ".gif"
        } else {
            mImageTitle.replace("/".toRegex(), "-") + ".jpg"
        }
    }

    /**
     * 复制文件
     */
    private fun copyFile(oldPath: String, newPath: String) {
        try {
            var bytesum = 0
            var byteread = 0
            val oldfile = File(oldPath)
            if (oldfile.exists()) { //文件存在时
                val inStream: InputStream = FileInputStream(oldPath) //读入原文件
                val fs = FileOutputStream(newPath)
                val buffer = ByteArray(1444)
                var length: Int
                while (inStream.read(buffer).also { byteread = it } != -1) {
                    bytesum += byteread //字节数 文件大小
                    //                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread)
                }
                inStream.close()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 注意开权限
     */
    fun saveToLocal(context: Context, bitmap: Bitmap) {
        try {
            val appDir = context.getExternalFilesDir("shell")
            // 没有目录创建目录
            if (!appDir!!.exists()) {
                appDir.mkdir()
            }
            val file = File(appDir, "view_" + System.currentTimeMillis() + ".jpg")
            val out: FileOutputStream
            try {
                out = FileOutputStream(file)
                if (bitmap.compress(Bitmap.CompressFormat.PNG, 90, out)) {
                    out.flush()
                    out.close()
                    // 通知图库更新
                    val uri = Uri.fromFile(file)
                    val scannerIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri)
                    context.sendBroadcast(scannerIntent)
                }
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 生成单个view的bitmap，
     */
    fun createViewBitmap(v: View?): Bitmap? {
        if (v == null) {
            return null
        }
        val bitmap = Bitmap.createBitmap(v.width, v.height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        // 周边边透明
        canvas.drawColor(Color.TRANSPARENT)
        v.draw(canvas)
        return bitmap
    }
}